package com.gome.splunk.DataBase;

import com.gome.splunk.Common.TimeHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import android.support.constraint.R;

import java.util.ArrayList;
import java.util.List;
import java.lang.Object;

/**
 * Created by i.Recall_Star on 2017/5/8.
 */

public class ErrorInfoDAO {
    private static final String TAG = "ErrorInfoDAO";

    // 列定义
    private final String[] ORDER_COLUMNS = new String[] {"id", "networkType","operators","requestTime","responseCode","errorMessage","RUL","isUploading","systemVersion","systemType","IMEI","userName"};

    private Context context;
    private CustomDBHelper customerDBHelper;
    private ErrorInfoContext errorInfoContext;

    public ErrorInfoDAO(Context context) {
        this.context = context;
        customerDBHelper = new CustomDBHelper(context);
        errorInfoContext = new ErrorInfoContext(context);
    }

    // 判断数据库中是否有数据
    public boolean isDataExist(){
        int count = 0;

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = customerDBHelper.getReadableDatabase();
            // select count(Id) from ErrorInfoDao
            cursor = db.query(CustomDBHelper.TABLE_NAME, new String[]{"COUNT(Id)"}, null, null, null, null, null);

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
            if (count > 0) return true;
        }
        catch (Exception e) {
            Log.e(TAG, "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return false;
    }

    /**
     * 初始化一些数据 用来做测试
     */
    public void initTable(){
        SQLiteDatabase db = null;

        try {
            db =  customerDBHelper.getWritableDatabase();
            db.beginTransaction();

            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (1, 'wifi', '联通', '2017-05-09 17:00', 404, '网络异常', 'www.baidu.com', '0', '5.0', '三星 note12')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (2, '3G', '联通', '2017-05-09 17:01', 404, '网络异常', 'www.baidu.com', '1', '6.0', '三星 note11')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (3, '4G', '联通', '2017-05-09 17:02', 404, '网络异常', 'www.baidu.com', '0', '4.0', '三星 note10')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (4, '5G', '联通', '2017-05-09 17:03', 404, '网络异常', 'www.baidu.com', '1', '6.0', '三星 note9')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (5, '6G', '联通', '2017-05-09 17:04', 404, '网络异常', 'www.baidu.com', '0', '3.0', '三星 note8')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (6, '7G', '联通', '2017-05-09 17:05', 404, '网络异常', 'www.baidu.com', '1', '6.0', '三星 note7')");
            db.execSQL("insert into " + CustomDBHelper.TABLE_NAME + " (\"id\", \"networkType\",\"operators\",\"requestTime\",\"responseCode\",\"errorMessage\",\"RUL\",\"isUploading\",\"systemVersion\",\"systemType\") values (7, '8G', '联通', '2017-05-09 17:06', 404, '网络异常', 'www.baidu.com', '0', '2.0', '三星 note6')");

            db.setTransactionSuccessful();
        }catch (Exception e){
            Log.e(TAG, "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }
    // 执行自定义的 sql
//    public void execSQL(String sql) {
//        SQLiteDatabase db = null;
//        try {
//            if (sql.contains("select")){
//                Toast.makeText(context, R.string.strUnableSql, Toast.LENGTH_SHORT).show();
//            }else if (sql.contains("insert") || sql.contains("update") || sql.contains("delete")){
//                db = customerDBHelper.getWritableDatabase();
//                db.beginTransaction();
//                db.execSQL(sql);
//                db.setTransactionSuccessful();
//                Toast.makeText(context, R.string.strSuccessSql, Toast.LENGTH_SHORT).show();
//            }
//        } catch (Exception e) {
//            Toast.makeText(context, R.string.strErrorSql, Toast.LENGTH_SHORT).show();
//            Log.e(TAG, "", e);
//        } finally {
//            if (db != null) {
//                db.endTransaction();
//                db.close();
//            }
//        }
//    }
    public void execSQL(String sql) {
        SQLiteDatabase db = null;
        try {
            if (sql.contains("select")){
                Toast.makeText(context, "Sorry，还没处理select语句", Toast.LENGTH_SHORT).show();
            }else if (sql.contains("insert") || sql.contains("update") || sql.contains("delete")){
                db = customerDBHelper.getWritableDatabase();
                db.beginTransaction();
                db.execSQL(sql);
                db.setTransactionSuccessful();
                Toast.makeText(context, "执行SQL语句成功", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "执行出错，请检查SQL语句", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }

    /**
     * 查询数据库中所有"未上传的数据"数据
     */
    public List<ErrorInfo> getAllDate(){
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = customerDBHelper.getReadableDatabase();
            // select * from Orders
            cursor = db.query(CustomDBHelper.TABLE_NAME, ORDER_COLUMNS, "isUploading = ?", new String[] {"0"}, null, null, null);

            if (cursor.getCount() > 0) {
                List<ErrorInfo> orderList = new ArrayList<ErrorInfo>(cursor.getCount());
                while (cursor.moveToNext()) {
                    orderList.add(parseErrorInfo(cursor));
                }
                return orderList;
            }
        }
        catch (Exception e) {
            Log.e(TAG, "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return null;
    }

    /**
     * 修改数据将 isUploading 值为"0"的改为1
     */
    public boolean updateOrder(){
        SQLiteDatabase db = null;
        try {
            db =  customerDBHelper.getWritableDatabase();
            db.beginTransaction();

            // update ErrorInfo set isUploading = '1' where isUploading = '0'
            ContentValues cv = new ContentValues();
            cv.put("isUploading", "1");
            db.update(CustomDBHelper.TABLE_NAME,
                    cv,
                    "isUploading = ?",
                    new String[]{"0"});
            db.setTransactionSuccessful();
            return true;
        }
        catch (Exception e) {
            Log.e(TAG, "", e);
        }
        finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

        return false;
    }

    /**
     * 新增一条数据
     */
    public boolean insertDate(ErrorInfo errorInfo){
        SQLiteDatabase db = null;

        try {
            db = customerDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues contentValues = new ContentValues();
            // {"id", "networkType","operators","requestTime","responseCode","errorMessage","RUL","isUploading","systemVersion","systemType"}
            contentValues.put("id", TimeHelper.currentTimeMillis());
            contentValues.put("networkType", errorInfo.getNetworkType());
            contentValues.put("operators", errorInfo.getOperators());
            contentValues.put("requestTime", errorInfo.getRequestTime());
            contentValues.put("responseCode", errorInfo.getResponseCode());
            contentValues.put("errorMessage", errorInfo.getErrorMessage());
            contentValues.put("RUL", errorInfo.getRUL());
            contentValues.put("isUploading", errorInfo.getIsUploading());
            contentValues.put("systemVersion", errorInfo.getSystemVersion());
            contentValues.put("systemType", errorInfo.getSystemType());
            contentValues.put("IMEI", errorInfo.getIMEI());
            contentValues.put("userName", errorInfo.getUserName());
            db.insertOrThrow(CustomDBHelper.TABLE_NAME, null, contentValues);

            db.setTransactionSuccessful();
            return true;
        }catch (SQLiteConstraintException e){
            Toast.makeText(context, "主键重复", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Log.e(TAG, "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }


    public ErrorInfo parseErrorInfo(Cursor cursor){
        ErrorInfo errInfo = new ErrorInfo();
        if (cursor != null){

            errInfo.operators = cursor.getString(cursor.getColumnIndex("operators"));
            errInfo.networkType = cursor.getString(cursor.getColumnIndex("networkType"));
            errInfo.requestTime = cursor.getString(cursor.getColumnIndex("requestTime"));
            errInfo.errorMessage = cursor.getString(cursor.getColumnIndex("errorMessage"));
            errInfo.RUL = cursor.getString(cursor.getColumnIndex("RUL"));
            errInfo.systemVersion = cursor.getString(cursor.getColumnIndex("systemVersion"));
            errInfo.systemType = cursor.getString(cursor.getColumnIndex("systemType"));
            errInfo.isUploading = cursor.getString(cursor.getColumnIndex("isUploading"));
            errInfo.responseCode = cursor.getInt(cursor.getColumnIndex("responseCode"));
            errInfo.IMEI = cursor.getString(cursor.getColumnIndex("IMEI"));
            errInfo.userName = cursor.getString(cursor.getColumnIndex("userName"));
        }
        return errInfo;
    }
}
